const md5 = require('md5')
const jwt = require('jsonwebtoken')
const util = require('util');

module.exports = async function (req, res, proceed) {
  try{
    const token = req.cookies.token
    
    if(!token){
      return res.view('pages/timeout')
    }
    
    const mtoken = md5(token)
    
    let secret = await sails.getDatastore('redis').leaseConnection(async (db)=>{
      var found = await (util.promisify(db.get).bind(db))(mtoken + ':secret');
      if (found == null || found == "" || found == undefined) {
        console.log("Redis缓存过期");
        return res.view('pages/timeout')
      }else{
        return found
      }
    })

    var rs;
    
    try{
      rs = jwt.verify(token,secret)
    }catch(TokenExpiredError){
      console.log(TokenExpiredError)
      return res.view('pages/timeout')
    }
    
    const userId = rs.userId

    const user = await User.findOne({id:userId})

    const token_exp = 60*30
    //生成JSONWEBTOKEN
    const ntoken = jwt.sign({ userId: userId }, secret, { expiresIn: token_exp })

    //将token存入cookie中传到客户端
    res.cookie('token', ntoken, { maxAge: token_exp * 1000, httpOnly: true })

    const nmtoken = md5(ntoken) //将token进行md5加密减少字符串长度，方便存入Redis

    await sails.getDatastore('redis').leaseConnection(async (db)=>{
      await (util.promisify(db.setex).bind(db))(nmtoken + ':secret', token_exp, secret)
    });
    
    res.view({"userName":user.userName})
    
    return true
  }catch(error){
    return res.view('pages/exception')
  }
};